package com.uiotsoft.small.app.sampler.mqtt;

import com.uiotsoft.small.app.entity.AppClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;

import java.text.MessageFormat;

@Slf4j
public class DisConnectSampler extends AbstractJavaSamplerClient {
    private AppClient appClient;
    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        SampleResult results = new SampleResult();
        results.setDataEncoding("UTF-8");
        JMeterVariables vars = JMeterContextService.getContext().getVariables();
        appClient = (AppClient) vars.getObject("appClient");
        MqttClient mqttClient = this.appClient.getMyMqttClient().getMqttClient();
        if (mqttClient == null) {
            results.sampleStart();
            results.setSuccessful(false);
            results.setResponseMessage("Connection not found.");
            results.setResponseData("Failed. Connection not found.".getBytes());
            results.setResponseCode("500");
            results.sampleEnd();
            return results;
        }else{
            try {
                results.sampleStart();
                if (mqttClient != null) {
                    log.info(MessageFormat.format("Disconnect connection {0}.", mqttClient));
                    mqttClient.disconnect();
                    mqttClient.close();
                    vars.remove("appClient");
                }

                results.sampleEnd();
                results.setSuccessful(true);
                results.setResponseData("Successful.".getBytes());
                results.setResponseMessage(MessageFormat.format("Connection {0} disconnected.", mqttClient));
                results.setResponseCodeOK();
            } catch (MqttException e) {
                results.sampleEnd();
                results.setSuccessful(false);
                results.setResponseMessage(MessageFormat.format("Failed to disconnect Connection {0}.", mqttClient));
                results.setResponseData(MessageFormat.format("Client [{0}] failed. Couldn't disconnect connection.", mqttClient.getClientId() == null ? "null" : mqttClient.getClientId()).getBytes());
                results.setResponseCode("501");
            }
        }
        return results;
    }
}
